﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class UserControl_ControlDetailPhanChiaDS : System.Web.UI.UserControl
{
    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["TDV"] != null)
            {
                ViewState["TDV"] = Request.QueryString["TDV"].ToString();
                LoadGrid(Request.QueryString["TDV"].ToString());
                LoadInfoTDV(Request.QueryString["TDV"].ToString());
                LoadGridTDV();
            }
        }
    }
    void LoadInfoTDV(string salesp_key)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            lblTDV.Text = dt.GetDataDepend(str, "k_getInforTDV", CommandType.StoredProcedure, ref error,
                new SqlParameter("@salesp_key", salesp_key));
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void LoadGrid(string salesp_key)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getDetailPhanChiaDS]", CommandType.StoredProcedure,
                new SqlParameter("@salesp_key", salesp_key));
            if (db.Rows.Count > 0)
            {
                grvTDV.DataSource = db;
                ViewState["KhoHangTemp"] = db;
            }
            else
            {
                grvTDV.DataSource = null;
            }
            grvTDV.DataBind();
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void imgBtnSave_Click(object sender, ImageClickEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            int i = 1;
            //chia đều
            if (RadioSelect.SelectedValue == "0")
            {
                if (grvTDV.Rows.Count > 0)
                {
                    

                    foreach (GridViewRow grv in grvTDV.Rows)
                    {
                        Label lblToSalesKey = (Label)grv.FindControl("lblsalesp_key");

                        dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_InsertSplitOfftakeDef", ref error,
                            new SqlParameter("@ToSalesKey", lblToSalesKey.Text),
                            new SqlParameter("@FrSalesKey", ViewState["TDV"].ToString()),
                            new SqlParameter("@Deno", grvTDV.Rows.Count),
                            new SqlParameter("@Nume", 1),
                            new SqlParameter("@i", i),
                            new SqlParameter("@Username", Session["user"].ToString()));
                        i++;
                    }
                    ShowMessageBox("Bạn đã lưu thông tin thành công");
                }
                else
                {
                    ShowMessageBox("Bạn chưa chọn TDV cho việc phân chia doanh số");
                }
               
            }//chia theo tùy chọn
            else if (RadioSelect.SelectedValue == "1")
            {
                if (grvTDV.Rows.Count > 0)
                {
                    float Total = 0;
                    foreach (GridViewRow grv in grvTDV.Rows)
                    {
                       
                        TextBox txtRate = (TextBox)grv.FindControl("txtRate");
                        if (txtRate.Text == "")
                        {
                            txtRate.Text = "0";
                        }
                        Total = Total + float.Parse(txtRate.Text);
                    }
                    if (Total == 100)
                    {
                        foreach (GridViewRow grv in grvTDV.Rows)
                        {
                            Label lblToSalesKey = (Label)grv.FindControl("lblsalesp_key");
                            TextBox txtRate = (TextBox)grv.FindControl("txtRate");
                            if (txtRate.Text == "")
                            {
                                txtRate.Text = "0";
                            }
                            dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_InsertSplitOfftakeDef", ref error,
                               new SqlParameter("@ToSalesKey", lblToSalesKey.Text),
                               new SqlParameter("@FrSalesKey", ViewState["TDV"].ToString()),
                               new SqlParameter("@Deno", 10),
                               new SqlParameter("@Nume", float.Parse(txtRate.Text) / 10),
                               new SqlParameter("@i", i),
                               new SqlParameter("@Username", Session["user"].ToString()));
                            i++;
                        }
                        ShowMessageBox("Bạn đã lưu thông tin thành công");
                    }
                    else
                    {
                        ShowMessageBox("Chỉ số tổng của các TDV không bằng 100 nên không lưu thông tin thành công");
                    }
                }
                else
                {
                    ShowMessageBox("Bạn chưa chọn TDV cho việc phân chia doanh số");
                }
            }
            else
            {
                dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "k_InsertSplitOfftakeDef", ref error,
                           new SqlParameter("@ToSalesKey", ViewState["TDV"].ToString()),
                           new SqlParameter("@FrSalesKey", ViewState["TDV"].ToString()),
                           new SqlParameter("@Deno", 1),
                           new SqlParameter("@Nume", 1),
                           new SqlParameter("@i", i),
                           new SqlParameter("@Username", Session["user"].ToString()));
                ShowMessageBox("Bạn đã lưu thông tin thành công");
               
            }
            
            LoadGrid(ViewState["TDV"].ToString());
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void imgBtnBack_Click(object sender, ImageClickEventArgs e)
    {
        Response.Redirect(webapp4U.Globals.ApplicationPath + "Pages/PhanChiaDS/Default.aspx");
    }
    void ShowMessageBox(string text)
    {
        MessageBox.Text = text;
        MessageBox.ShowOnPageLoad = true;
    }
    protected void grvTDV_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {

                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblMaSo = (Label)grv.FindControl("lblsalesp_key");
                DataTable table = new DataTable();
                table = (DataTable)ViewState["KhoHangTemp"];

                int i = 0;
                foreach (DataRow dr in table.Rows)
                {
                    if (dr[0].ToString() == lblMaSo.Text)
                    {
                        table.Rows[i].Delete();
                        table.AcceptChanges();
                        ViewState["KhoHangTemp"] = table;

                        grvTDV.DataSource = ViewState["KhoHangTemp"];
                        grvTDV.DataBind();
                        return;
                    }
                    i++;
                }
                
            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void LoadGridTDV()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
           

            DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_getTDVFilterAdncodePhanChiaDS]", CommandType.StoredProcedure,
                new SqlParameter("@Username", Session["user"].ToString()));


            grvSelectTDV.DataSource = db;
            grvSelectTDV.DataBind();

        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvSelectTDV_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {

                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblMaSo = (Label)grv.FindControl("lblsalesp_key");
                Label lblHoten = (Label)grv.FindControl("lblDescription");
                UpdateGridProduct(lblMaSo.Text, lblHoten.Text);

            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void UpdateGridProduct(string salesp_key, string salesp_name)
    {
        dt = new ClassExecute.ClassExecute();
        DataTable table = new DataTable();
        if (ViewState["KhoHangTemp"] != null)
        {
            table = (DataTable)ViewState["KhoHangTemp"];
            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() == salesp_key)
                {
                    return;
                }
            }

            DataRow row = table.NewRow();
            //Fill All Columns with Data
            row[0] = salesp_key;
            row[1] = salesp_name;
            row[2] = "0";

            table.Rows.Add(row);
        }
        else
        {


            DataColumn col1 = new DataColumn("ToSalesKey");
            DataColumn col2 = new DataColumn("salesp_name");
            DataColumn col3 = new DataColumn("Rate");
           


            col1.DataType = System.Type.GetType("System.String");
            col2.DataType = System.Type.GetType("System.String");
            col3.DataType = System.Type.GetType("System.String");
           

            table.Columns.Add(col1);
            table.Columns.Add(col2);
            table.Columns.Add(col3);
           

            //Create a Row in the DataTable table
            DataRow row = table.NewRow();
            //Fill All Columns with Data
            row[col1] = salesp_key;
            row[col2] = salesp_name;
            row[col3] = "0";
           

            table.Rows.Add(row);

            ViewState["KhoHangTemp"] = table;
        }

        grvTDV.DataSource = ViewState["KhoHangTemp"];
        grvTDV.DataBind();


    }
}